<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/2/28
 * Time: 19:40
 */

namespace app\common\model;

use think\Cache;

/**
 * 用户播放记录模型
 * Class ZhunleCourseSection
 * @package app\common\model
 */
class ZhunleCourseSectionPlay extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_course_section_play';

    const UserAllPlay = ':user:course:play:ids:';//用户播放的所有课程id
    const UserCoursePlay = ':user:course:play:id:';//用户当前课程播放的章节id
    const CACHE_TIME = 86400 * 7;

    /**
     * 删除用户播放记录缓存
     * @param array $map
     */
    public function rm_cache($map = [])
    {
        $uid = $map['uid'];
        $cid = $map['cid'];

        Cache::rm($uid . self::UserAllPlay);
        Cache::rm($uid . self::UserCoursePlay . $cid);
        return;
    }


    /**
     * 保存用户播放记录
     * @param array $map
     * @return bool
     */
    public function savePlayId($map = [])
    {
        $cid = $map['cid'];
        $uid = $map['uid'];
        $csid = $map['csid'];

        // 获取用户已播放的记录,判断当前课程是否已播放
        $data = $this->getPlayId(['uid' => $uid]);

        $cids = [];

        if ($data)
        {
            foreach ($data as $datum)
            {
                $cids[] = $datum['cid'];
            }
        }
        // 已播放,更新最后播放的视频记录
        if (in_array($cid, $cids))
        {
            try
            {
//                $this->where(['cid'=>$cid,'uid'=>$uid])->update(['is_last_csid'=>$csid]);
                self::update(['is_last_csid' => $csid], ['cid' => $cid, 'uid' => $uid]);

                $this->rm_cache(['cid' => $cid, 'uid' => $uid]);
            }
            catch (\Exception $e)
            {
                $this->error = '保存播放记录失败';

                return false;
            }
        }// 未播放,添加新数据
        else
        {
            try
            {
                $this->save(
                    [
                        'cid' => $cid,
                        'uid' => $uid,
                        'is_last_csid' => $csid
                    ]
                );
                $this->rm_cache(['cid' => $cid, 'uid' => $uid]);
            }
            catch (\Exception $e)
            {
                $this->error = '保存播放记录失败';

                return false;
            }
        }

        return true;
    }

    /**
     * 获取当前用户所有已播放的记录
     * @param array $map
     * @return array|bool
     */
    public function getPlayId($map = [])
    {
        $uid = $map['uid'];

        $data_list = [];

        $all_course_ids = false;

        if ($this->cache_on >= 1)
        {
            $all_course_ids = Cache::get($uid . self::UserAllPlay);
        }

        if ($all_course_ids === false)
        {
            try
            {
                $data = $this->where(['uid' => $uid])->column('cid');

                // 将课程id组成字符串
                if (!empty($data))
                {
                    $all_course_ids = implode(',', $data);
                }

                // 缓存课程id,根据课程id
                if ($all_course_ids && $this->cache_on >= 1)
                {
                    Cache::set($uid . self::UserAllPlay, $all_course_ids, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $this->error = '获取用户播放记录失败';
                return false;
            }
        }

        $all_course_id = explode(',', $all_course_ids);

        // 根据当前页课程id获取所需的课程信息
        if (!empty($all_course_id))
        {
            $ac_ids = '';
            $temp = [];

            // 从缓存课程内容,根据课程id
            foreach ($all_course_id as $ac_id)
            {
                if ($this->cache_on >= 1)
                {
                    // 根据课程id 获取课程内容
                    $temp[$ac_id] = Cache::get($uid . self::UserCoursePlay . $ac_id);
                } else
                {
                    // 缓存未开启时，默认从数据库获取
                    $temp[$ac_id] = false;
                }
                // 课程内容未缓存，等待从数据库中获取
                if ($temp[$ac_id] === false && $ac_id)
                {
                    $ac_ids .= ',' . $ac_id;
                }
            }

            // 从数据库获取课程内容
            if ($ac_ids != '' || strlen($ac_ids) > 0)
            {
                // 去掉开头的,
                $ac_ids = substr($ac_ids, 1);
                try
                {
                    $course = $this
                        ->field('cid,is_last_csid')
                        ->where('cid in(' . $ac_ids . ')')
                        ->where('uid', $uid)
                        ->select();

                    $course = json_decode(json_encode($course, true), true);

                }
                catch (\Exception $e)
                {
                    $this->error = '获取用户当前课程播放记录失败';
                    return false;
                }

                if (!empty($course))
                {
                    foreach ($course as $c)
                    {
                        // 将课程内容缓存
                        if ($this->cache_on >= 1)
                        {
                            Cache::set($uid . self::UserCoursePlay . $c['cid'], $c, self::CACHE_TIME);
                        }
                        // 将数据库查出来的内容 写入到数组中为空的部分
                        if ($c)
                        {
                            $temp[$c['cid']] = $c;
                        }
                    }
                }
            }

            foreach ($temp as $item)
            {
                if ($item)
                {
                    $data_list[] = $item;
                }
            }
        }
        return $data_list;
    }
}
